package com.lzp.java.concurrent.threadcore.stopthread.wrongways;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 当线程陷入到阻塞时，volatile方式无法停止线程--通过控制台可以看到
 * <p>
 * 本例中，生产者队列生产速度很快，很容易充满队列，进入阻塞等待消费者消费。
 *
 * @author lzp
 * @date 2020/02/01
 */
public class WrongWayVolatileCantStop {

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue storage = new ArrayBlockingQueue(10);

        Producer producerTask = new Producer(storage);
        Thread producer = new Thread(producerTask);
        producer.start();
        Thread.sleep(3000);

        Consumer consumer = new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.storage.take() + "被消费者消费");
            Thread.sleep(100);
        }
        System.out.println("消费者不再需要更多数据");

        // 停止生产者
        producerTask.flag = true;
        System.out.println(producerTask.flag);
    }

}

class Producer implements Runnable {
    public volatile boolean flag = false;
    BlockingQueue storage;

    public Producer(BlockingQueue storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        // 生产100的倍数，到仓库
        int num = 1;
        try {
            while (num <= 5000 && !flag) {
                if (num % 100 == 0) {
                    storage.put(num);
                    System.out.println("生产者生产" + num + "放入仓库");
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者结束运行");
        }
    }
}

class Consumer {
    BlockingQueue storage;

    public Consumer(BlockingQueue storage) {
        this.storage = storage;
    }

    public boolean needMoreNums() {
        if (Math.random() > 0.95) {
            return false;
        }
        return true;
    }
}